# 服务端_block
# from socket import *
# import subprocess
# import struct
#
# ip_port = ('127.0.0.1', 8000)
# buffer_size = 1024
# backlog = 5
#
# tcp_server = socket(AF_INET, SOCK_STREAM)
# tcp_server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)  # 就是它，在bind前加
# tcp_server.bind(ip_port)
# tcp_server.listen(backlog)
#
# while True:
#     conn, addr = tcp_server.accept()
#     print('新的客户端链接：', addr)
#     while True:
#         try:
#             cmd = conn.recv(buffer_size)
#             print('收到客户端命令:', cmd.decode('utf-8'))
#
#             # 执行命令cmd，得到命令的结果cmd_res
#             res = subprocess.Popen(cmd.decode('utf-8'), shell=True,
#                                    stderr=subprocess.PIPE,
#                                    stdout=subprocess.PIPE,
#                                    stdin=subprocess.PIPE,
#                                    )
#             err = res.stderr.read()
#             if err:
#                 cmd_res = err
#             else:
#                 cmd_res = res.stdout.read()
#             if not cmd_res:
#                 cmd_res = '执行成功'.encode('gbk')
#             # 解决粘包
#             length = len(cmd_res)
#             data_length = struct.pack('i', length)
#             conn.send(data_length)
#             conn.send(cmd_res)
#         except Exception as e:
#             print(e)
#             break
#     conn.close()

# 服务端 non_block
import socketserver


class Myserver(socketserver.BaseRequestHandler):
    """socketserver内置的通信方法"""
    def handle(self) -> None:
        print(f"conn is: {self.request}")  # conn
        print(f"addr is: {self.client_address}")  # addr

        while True:
            try:
                # receive message
                data = self.request.recv(1024)
                if not data: break
                print(f"收到的客户端消息是: {data.decode('utf-8')}, {self.client_address}")

                # send message
                self.request.sendall(data.upper())
            except Exception as e:
                print(e)
                break
if __name__ == '__main__':
    s = socketserver.ThreadingTCPServer(('127.0.0.1', 8000), Myserver)
    print(s.server_address)
    print(s.RequestHandlerClass)
    print(Myserver)
    print(s.socket)
    s.serve_forever()





























